package com.cloud.spock.groovy.test

import static org.junit.Assert.*

import org.junit.Test
import spock.lang.Specification
import com.cloud.spock.test.DbEntity
import com.cloud.spock.test.DbEntityDao
import com.cloud.spock.test.MyService

class MockTest extends Specification{

	def mockRquestNo1 = "456";
	def "校验mock对象调用次数"(){
		given:
		DbEntity expectEntity = new DbEntity();
		//groovy的with语法,简化创建对象
		expectEntity.with {
			id = 456
			requestNo = mockRquestNo1;
		}
		//mock跟stub不同的是可以校验mock对象调用的次数.
		DbEntityDao dao = Mock(DbEntityDao);
		MyService service = new MyService();
		//Groovy里面所有的field都是public的,可以直接访问
		service.dbEntityDao = dao;
		when:
		long id = service.selectByRequestNo(mockRquestNo1);
		then:
		id ==456
		//then除了验证结果,还可以甚至mock对象的返回值.
		//Spock 会先解析then中定义的mock,等when执行后后再校验mock行为
		1*dao.selectByRequestNo(mockRquestNo1) >>expectEntity;
	}

	def "抓取输入值"(){
		given:
		def resultCapture = null
		DbEntityDao dao = Stub(DbEntityDao.class)
		//定义lambda表达式,抓取输入值
		dao.selectByRequestNo({v->resultCapture =v})>>null
		when:
		dao.selectByRequestNo("123")
		then:
		resultCapture == "123"
	}



}
